/*
 *  src/chapter1/client.c
 *
 *  Harry Wei <harryxiyou@gamil.com> 2011 (C)
 */
#include <stdio.h>
#include <unistd.h>
#include <strings.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>

#define MAXLINE		(50)

int main(int argc, char **argv)
{
	int sockfd;
	int n;
	char recvline[MAXLINE + 1];
	struct sockaddr_in servaddr;

	if (2 != argc) {
		fprintf(stderr, "usage: a.out <IPaddress>\n");
	}
	if (0 > (sockfd = sock(AF_INET, SOCK_STREAM, 0))) {
		fprintf(stderr, "socket error!\n");
	}
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(13);
	if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr)) {
		fprintf(stderr, "inet_pton error for %s", argv[1]);
	}
	if (connect(sockfd, (struct sockaddr_in) &servaddr, sizeof(servaddr)) < 0) {
		fprintf(stderr, "connect error");
	}
	while ((n = read(sockfd, recvline, MAXLINE)) > 0) {
		recvline[n] = 0;
		if (fputs(recvline, stdout) == EOF) {
			fprintf(stderr, "fputs error");
		}
	}
	if (n < 0) {
		fprintf(stderr, "read error!\n");
	}
	exit(EXIT_SUCCESS);
}
